import {put, take, call, fork, select} from 'redux-saga/effects'
import {get, post} from '../axios'
import {actionsTypes as IndexActionTypes} from '../reducers'
import {actionsTypes as UserActionTypes} from '../reducers/user'
import history from '../history';
import utils from '../common/utils'

export function* login(data) {
    yield put({type: IndexActionTypes.FETCH_START});
    try {
        return yield call(post, '/mem/login', data)
    } catch (error) {
        yield put({type:IndexActionTypes.SET_MESSAGE,msgContent:'用户名或密码错误',msgType:'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END});
    }
}

export function* register (data) {
    yield put({type:IndexActionTypes.FETCH_START});
    try {
        return yield call(post, '/mem/register', data)
    } catch (error) {
        yield put({type:IndexActionTypes.SET_MESSAGE,msgContent:'注册失败',msgType:'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END});
    }
}

export function* logout () {
    yield put({type: IndexActionTypes.FETCH_START})
    try {
        return yield call(get, '/mem/logout')
    } catch (error) {
        yield put({type:IndexActionTypes.SET_MESSAGE,msgContent:'网络错误',msgType:'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END});
    }
}

export function* get_user_info () {
    yield put({type:IndexActionTypes.FETCH_START});
    try {
        return yield call(get, '/mem/me')
    } catch (error) {
        yield put({type:IndexActionTypes.SET_MESSAGE, msgContent:'网络错误', msgType:'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END});
    }
}
// 登陆||注册成功，决定跳去哪
var nextStep = function* (res) {
    console.log(window.location.pathname)
    // 当前在 invitereg 页面不直接跳，由用户自己点击跳转
    if (window.location.pathname.indexOf('invitereg')!==-1 ){
        console.log(11)
        //根据手机号是否注册，显示不同的文本
        let status,msg
        if (!res.isNewUser) {
            status = 'invalid'
            msg = '该手机已绑定会员'
        } else {
            status = 'valid'
            msg = '注册成功'
            let _m = /invitereg\/(\w+)/g.exec(window.location.pathname)
            let invite_code = _m&&_m[1]
            yield put({type:UserActionTypes.BIND_INVITECODE, invite_code})
        }
        // yield put({type:InviteActionTypes.RESOLVE_REG, status, msg, shouldRender: true})
    } else {
        let entry = yield select(state => state.globalState.entry)
        if (res.isNewUser) {
            setTimeout( function () {
                history.push('/bind-invite-code')
            }, 1000)
    
        } else {
            setTimeout( function () {
                history.push(entry)
            }, 1000)
        }
    }

}

export function* loginFlow() {
    while (true) {
        let request = yield take(IndexActionTypes.USER_LOGIN);
        let response = yield call(login, request.data);
        if(response&&response.success){
            yield put({type:IndexActionTypes.SET_MESSAGE,msgContent:'登录成功!',msgType:'success'});
            yield put({type:IndexActionTypes.RESPONSE_TOKEN, data:response.data})
            yield put({type:UserActionTypes.GET_USER_INFO})
            yield call(nextStep, response)
        } else {
            yield put({type:IndexActionTypes.SET_MESSAGE,msgContent:'登录失败',msgType:'fail'});
        }
    }
}

export function* registerFlow () {
    while(true){
        let request = yield take(IndexActionTypes.USER_REGISTER);
        let response = yield call(register, request.data);
        if (response&&response.success) {
            yield put({type:IndexActionTypes.SET_MESSAGE,msgContent:'注册成功!',msgType:'success'});
            yield put({type:IndexActionTypes.RESPONSE_TOKEN, data:response.data})
            yield put({type:UserActionTypes.GET_USER_INFO})
            yield call( ()=>setTimeout( function () {
                history.push('/')
            }, 1000))
        } else {
            yield put({type:IndexActionTypes.SET_MESSAGE,msgContent:response.msg,msgType:'fail'});
        }

    }
}

export function* logoutFlow () {
    while (true) {
        let request = yield take(IndexActionTypes.USER_LOGOUT);
        let response = yield call(logout);
        if(response){
            localStorage.removeItem('invite_code')
            localStorage.removeItem('auth_token')
            localStorage.removeItem('openid')
            yield call( ()=>setTimeout( function () {
                history.push('/login')
            }, 1000))

        }
    }
}

export function* getUserInfoFlow () {
    while(true){
        let request = yield take(UserActionTypes.GET_USER_INFO);
        let response = yield call(get_user_info);
        if (response && response.success) {
            yield put({type:UserActionTypes.RESPONSE_USER_INFO, data: response.data});
        } 
    }
}

let isWechat = () => {
    let ua = navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i)=="micromessenger"
}  

export function* user_auth () {
    while(true){
        yield take(IndexActionTypes.USER_AUTH);
        try {
            let _pathname = window.location.pathname,
                redirect_url = '/',
                invite_id = utils.getQueryString('invite_id')
            
                console.log(invite_id)
            
            if (isWechat()) {
                yield put({type:IndexActionTypes.RESOLVE_ISWECHAT, isWechat: true})
            }
            /**
             * 先尝试登陆，登陆成功=》进入页面
             * 登陆失败： 判断是否是微信环境
             * 微信：微信授权
             * 不是微信：进入登陆页
             */
            yield put({type:IndexActionTypes.FETCH_START});
            let response = yield call(get, '/mem/me');
            if (response && response.success){
                yield put({type:IndexActionTypes.CHANGE_SHOULDRENDER, shouldRender: true})
                yield put({type:UserActionTypes.RESPONSE_USER_INFO, data:response.data})
            } else if (isWechat()) {
                yield call( ()=>window.location.href=`/wechat/login?redirect_url=${encodeURIComponent(redirect_url)}&invite_code=${invite_id}` )
            } else {
                yield put({type:IndexActionTypes.CHANGE_SHOULDRENDER, shouldRender: true})
                yield call( ()=> history.push('/login'))
            }
        }catch (err){
            console.log(err);
        }finally {
            yield put({type: IndexActionTypes.FETCH_END});
        }
    }
}

  